class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def equalToDescendants(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        self.ans = 0
        def dfs(node):
            left_val = 0
            right_val = 0
            if node.left:
                left_val = dfs(node.left)
            if node.right:
                right_val = dfs(node.right)
            if node.val == left_val + right_val:
                self.ans += 1
            return node.val + left_val + right_val
        dfs(root)
        return self.ans
